package com.wwg.threadSort;

import java.util.concurrent.CountDownLatch;

/**
 * @author: wwg
 * @date: 2022/3/11 17:46
 */


/**
 * CountDownLatch控制线程顺序执行
 */
public class ThreadSortCountDownLatch {

    /**
     * 用于判断线程一是否执行，倒计时设置为1，执行后减1
     */
    private static final CountDownLatch c1 = new CountDownLatch(1);

    /**
     * 用于判断线程二是否执行，倒计时设置为1，执行后减1
     */
    private static final CountDownLatch c2 = new CountDownLatch(1);

    public static void main(String[] args) {
        final Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "执行");
                //对c1倒计时-1
                c1.countDown();
            }
        },"t1");

        final Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //等待c1倒计时，计时为0则往下运行
                    c1.await();
                    System.out.println(Thread.currentThread().getName() + "执行");
                    //对c2倒计时-1
                    c2.countDown();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"t2");

        Thread thread3 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //等待c2倒计时，计时为0则往下运行
                    c2.await();
                    System.out.println(Thread.currentThread().getName() + "执行");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"t3");

        thread3.start();
        thread1.start();
        thread2.start();
    }
}
